﻿using Microsoft.AspNetCore.Mvc;
using ProjectScheduling_web.dao;
using ProjectScheduling_web.model;
using ProjectScheduling_web.model.Enums;

namespace ProjectScheduling_web.Controllers.U
{
    public class SalerController : BController
    {
        private static readonly MemberDao @base = MemberDao.Base;
        [HttpGet]
        public IActionResult Search(int page, int row, string key = "", int org = 0)
        {
            var lst = @base.FindAll(page, row, it =>
                    (string.IsNullOrEmpty(key) || (it.Name != null && it.Name.Contains(key))) &&
                    (org == 0 || it.OrgId == org)
                    );
            lst?.Items?.ForEach(item =>
            {
                item.Password = null;
                item.Token = null;
            });
            return Success(lst);
        }
        [HttpPost]
        public IActionResult Add([FromBody] Member req)
        {
            if (req == null) return Fail("数据有误");
            if (string.IsNullOrEmpty(req.Password)) return Fail("密码不能为空");
            if (string.IsNullOrEmpty(req.Name)) return Fail("姓名不能为空");
            if (@base.Exists(it => it.Name == req.Name))
                return Fail("当前销售员已存在，请勿重复添加");
            req.Password = Common.Md5(req.Password?.Trim() ?? "");
            req.CreateTime = DateTime.Now;
            @base.Add(req);
            return Success("创建成功");
        }
        [HttpPost]
        public IActionResult Update([FromBody] Member req)
        {
            if (req == null) return Fail("数据有误");
            if (req.Id == 0) return Fail("获取销售员信息有误");
            if (string.IsNullOrEmpty(req.Name)) return Fail("姓名不能为空");
            if (@base.Exists(it => it.Name == req.Name && it.Id != req.Id))
                return Fail("当前登录名不能重复");
            var org = DictionaryDataDao.Base.Find(z => z.Category == EnumDictionaryCategory.部门 && z.Value == req.OrgId);
            if (org == null) return Fail("部门不存在，请检查");
            req.OrgName = org.Name;
            if (!string.IsNullOrEmpty(req.Password))
            {
                req.Password = Common.Md5(req.Password?.Trim() ?? "");
                @base.Update(req, it => new { it.Name, it.Phone, it.OrgId, it.OrgName, it.TrueName, it.Sex, it.IsLock, it.IsAdmin, it.Password });
            }
            else
            {
                @base.Update(req, it => new { it.Name, it.Phone, it.OrgId, it.OrgName, it.TrueName, it.Sex, it.IsLock, it.IsAdmin });
            }
            return Success("修改成功");
        }
        [HttpGet]
        public IActionResult Remove(int id)
        {
            return id == 0 ? Fail("获取销售员信息有误") : @base.Delete(id) > 0 ? Success("删除成功") : Fail("删除失败");
        }
        [HttpGet]
        public IActionResult SearchName(int orgId = 0, string key = "")
        {
            return Success(@base.SearchName(orgId, key));
        }
    }
}
